import { useEffect, useRef, useState } from "react";
import styles from './index.module.sass';

interface Global {
    //输入clear: true时，会清空实例后，再装填图表
    isClear: boolean
}

interface Props {
    /**图表配置选项 */
    option: any

    /**扩展配置项 */
    global?: Global

    /**图表实例的处理函数 */
    handleChart?: Function
}

/**
 * echarts 基础组件
 * @param option 图表配置项
 * @returns 
 */
const ChartPanel: React.FC<Props> = ({
    option,
    global,
    handleChart
}) => {
    console.debug('ChartPanel', option)

    const chartRef = useRef(null);
    const [chart, setChart] = useState<any>();

    const [isClear, setIsClear] = useState(!!global?.isClear);
    const [chartOption, setChartOption] = useState<any>(option);

    useEffect(() => {
        const _chart = echarts.init(chartRef.current);
        setChart(_chart);
        handleChart && handleChart(_chart);
        return () => { _chart.dispose() }
    }, [handleChart])

    useEffect(() => {
        if (global && typeof global.isClear !== 'undefined') {
            setIsClear(global.isClear);
        }
    }, [global]);

    useEffect(() => {
        setChartOption((val: any) => {
            if (option !== val) {
                return option;
            } else {
                return val;
            }
        });
    }, [option])

    useEffect(() => {
        if (chart && chartOption) {
            if (isClear) {
                chart.clear();
            }
            chart.setOption(chartOption);
        }
    }, [isClear, chartOption, chart])

    return (
        <article className={styles.chartPanel} ref={chartRef}></article>
    )
}

export default ChartPanel;